<style media="screen">
  div > h1 {
    margin-bottom: 20px;
  }
  .form {
    width: 50%;
}
</style>
<template>
    <div>
      <!-- <h1>使用iView自带的文件上传组件，方便快捷</h1>
      <Upload
          multiple
          type="drag"
          action="//jsonplaceholder.typicode.com/posts/">
          <div style="padding: 20px 0">
              <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
              <p>点击或将文件拖拽到这里上传</p>
          </div>
      </Upload> -->
      <div class="form">
        <i-form >
          <Form-item label="姓名" prop="text">
              <i-input v-model="text"  type="textarea" @on-blur="validateText" :autosize="{minRows: 2,maxRows: 5}" placeholder="文本上传"></i-input>
          </Form-item>
          <Form-item>
              <i-button type="primary" @click.native="handleSubmit()">提交</i-button>
              <i-button type="ghost" @click.native="handleReset()" style="margin-left: 8px">重置</i-button>
          </Form-item>
        </i-form>
        <div>
          交易结果：
          <p>{{ textHash }}</p>
        </div>
      </div>
      <div style="margin-top: 100px;">
          <Upload
              :before-upload="handleUpload"
              action="//jsonplaceholder.typicode.com/posts/">
              <Button type="ghost" icon="ios-cloud-upload-outline">选择图片上传</Button>
          </Upload>
          <div v-if="file !== null">文件名: {{ file.name }} <Button type="text" @click="upload" :loading="loadingStatus">{{ loadingStatus ? 'Uploading' : 'Click to upload' }}</Button></div>
          <p v-if="fileHash !== ''">文件Hash: {{ fileHash }} </p>

      </div>
      <!-- <div style="margin-top: 100px;">
        <Upload
              :before-upload="handleUpload"
              action="//jsonplaceholder.typicode.com/posts/">
              <Button type="ghost" icon="ios-cloud-upload-outline">选择图片验证</Button>
          </Upload>
          <div v-if="file !== null">文件名: {{ file.name }} <Button type="text" @click="upload" :loading="loadingStatus">{{ loadingStatus ? 'Uploading' : 'Click to upload' }}</Button></div>
      </div> -->
    </div>
</template>
<script>
import crypto from 'crypto';

    export default {
      data () {
          return {
              baseUrl: 'http://134.175.91.29:7000',
              file: null,
              loadingStatus: false,
              text: '',
              textHash: '',
              fileHash: '',
          }
      },
      // computed() {
      //   if(this.fileHash !== '') {
      //     this.$Message.success("图片Hash为：" + this.fileHash);
      //   }
      // },
      methods: {
         /**
            Liens使用的是sha256Hash算法
            通过Crypto模块，简单加密生成一个哈希值：
            var hash = crypto.createHash('sha256').update(data).digest()

            crypto.createHash('sha256')先用sha256算法创建一个Hash实例
            接着使用.update(data)接受明文data数据
            最后调用.digest()方法，获得加密字符串，即密文
            **/
          validateText() {
            var text = this.text;
            console.log("text: " + text);
            //TO-FIX json to restrict form of string
            //var str = " test,.23@#!$$k~!  @#$%^&*()(_+-=|\{}[]';:,./<>??gg  g~```hello, ，  world ! ！: ：";
            var str = this.text;
            console.log("str1: " + str);

            str=str.replace(/[\ |\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\-|\_|\+|\=|\||\\|\[|\]|\{|\}|\;|\:|\"|\'|\,|\<|\.|\>|\/|\?|\、|\，|\。|\？|\《|\》|\；|\‘|\：|\“|\【|\】|\{|\}|\·|\~|\！|\￥|\……|\（|\）|\——|\+]/g,""); 
            //console.log("str2: " + str);

            var hash1 = crypto.createHash('sha256').update(str, 'utf8').digest().toString('hex');
            //var hash2 = crypto.createHash('sha256').update("I", 'utf8').digest().toString('hex');
            this.textHash = hash1;
            
            //console.log("str2 hash256: " + hash1);
          },

          handleUpload (file) {
              var reader = new FileReader();
              var fileBase64;
              this.file = file;
              var this_ = this; // 取代异步file读取时的this
              var imgUrlBase64;
              // var imgText;
              if(file){
                //将文件以Data URL形式读入页面  
                imgUrlBase64 = reader.readAsDataURL(this.file);
                //imgText = reader.readAsText(file);
                console.log(this.file);
                //console.log(this.fileHash !== '');
                reader.onload = function (e) {
                  //var ImgFileSize = reader.result.substring(reader.result.indexOf(",") + 1).length;//截取base64码部分（可选可不选，需要与后台沟通）
                  
                  //执行上传操作
                  fileBase64 = reader.result;
                  // console.log(fileHash);
                  var hash2 = crypto.createHash('sha256').update(fileBase64, 'utf8').digest().toString('hex');
                  this_.fileHash = hash2;
                  console.log(this_.fileHash);
                  //console.log(this.fileHash !== '');
                }
              
              }
              return false;
          },
          upload () {
              //this.$Message.success(this.fileHash);
              this.loadingStatus = true;
              setTimeout(() => {
                  this.file = null;
                  this.fileHash = '';
                  this.loadingStatus = false;
                  this.$Message.success('Success')
              }, 1500);
          },
          handleSubmit(name) {
              
              this.$Message.success('上传成功');
          },
          handleReset(name) {
              //this.$Message.warning('这是一条警告的提示');
          }
      }
    }
</script>
